package day12.network;

import java.io.*;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Scanner;

public class ChatClient {
    private Socket s;
    private BufferedReader in;
    private PrintWriter out;
    private LinkedList<String> list = new LinkedList<>();
    //没有输入是false
    //开始输入内容是true
    private boolean inputFlag = false;

    public void start(){
        try {
            s = new Socket("127.0.0.1", 8000);
            in = new BufferedReader(new InputStreamReader(s.getInputStream(), "GBK"));
            out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), "GBK"));
            System.out.print("请输入昵称:");
            String name = new Scanner(System.in).nextLine();
            out.println(name); // 之前写的是write,所以错误
            out.flush();
            // 等待输入聊天内容，并发送
            new Thread(){
                @Override
                public void run() {
                    input();
                }
            }.start();
            // 等待接收聊天室内容，并显示
            new Thread(){
                @Override
                public void run() {
                    receive();
                }
            }.start();
            //打印线程
            new Thread(){
                @Override
                public void run() {
                    print();
                }
            }.start();

        }catch (Exception e){
            System.out.println("连接失败 ");
        }
    }

    private void print(){
        while (true) {
            synchronized (list) {
                while(inputFlag || list.size() == 0){
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(list.removeFirst());
            }
        }
    }

    private void receive() {
        try {
            String line;
            while ((line = in.readLine()) != null) {
                synchronized (list){
                    list.add(line);
                    list.notifyAll();
                }
                //System.out.println(line);
            }
        }catch (Exception e){

        }
        System.out.println("连接已断开");
    }
    private void input() {
        System.out.println("按回车开始输入");
        while(true){
            try{
                new Scanner(System.in).nextLine();
                inputFlag = true;
                System.out.print("输入聊天内容:");
                String msg = new Scanner(System.in).nextLine();
                out.println(msg);
                out.flush();
                //输入完成
                inputFlag = false;
                //通知打印线程
                synchronized (list){
                    list.notify();
                }
            }catch (Exception e){

            }
        }
    }

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        chatClient.start();
    }

}
